package com.bjpowernode.web.intercepter;

import com.alibaba.fastjson.JSONObject;
import com.bjpowernode.common.P2PConstants;
import com.bjpowernode.common.ResultObject;
import com.bjpowernode.model.User;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;


//做登录的拦截器
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取session中的user
        User user= (User) request.getSession().getAttribute(P2PConstants.SESSION_USER);

        //获取拦截的地址
//        StringBuffer url =request.getRequestURL();
//        String params =request.getQueryString();
//        System.out.println("url="+url+",params="+params);

        if (user==null){
            String header =request.getHeader("X-Requested-With");
            if ("XMLHttpRequest".equals(header)){
                //当前是ajax请求
                response.setContentType("application/json;charset=utf-8");
                PrintWriter writer=response.getWriter();

                ResultObject ro =new ResultObject(20000,"需要登录");
                writer.println(JSONObject.toJSONString(ro));
                writer.flush();
                writer.close();

            }else {
                //没有登录，重定向到登录页面
                response.sendRedirect(request.getContextPath()+
                        "/loan/page/login?returnUrl=http://localhost:8002/p2p/index");
            }
            return false;
        }
        return true;
    }
}
